var elementCtrl = {
	findParent: function(el, tag){
		while(el && el.tagName != tag){
			el = el.parentNode;
		}
		
		return el;
	},
	movePre: function(el){
		var parent = el.parentNode;
		
		var els = parent.children;
		var beforeElement = null;
		
		for (var i = 0, l = els.length; i < l; i++) {
			if (el === els[i]) {
				break;
			} else {
				beforeElement = els[i];
			}
		}
		
		parent.insertBefore(el, beforeElement);
	},
	moveNext: function(el){
		var parent = el.parentNode;
		var els = parent.children;
		var beforeElement = null;
		for (var i = els.length; i > -1; i--) {
			if (el === els[i]) {
				break;
			} else {
				beforeElement = els[i + 1];
			}
		}
		if (beforeElement) {
			parent.insertBefore(el, beforeElement);
		} else {
			parent.appendChild(el);
		}
	}
};
var tableCtrl = {
	removeRow: function(el){
		var row = elementCtrl.findParent(el, 'TR');
		var table = elementCtrl.findParent(el, 'TABLE');
		table.deleteRow(row.rowIndex);
	},
	insertRow: function(datas, table){
		for (var i = 0, l = datas.length; i < l; i++) {
			var data = datas[i];
			var row = table.insertRow();
			row.insertCell(0).innerHTML = data['title'];
			row.insertCell(1).innerHTML = data['price'];
			row.insertCell(2).innerHTML = [
				'<button type="button" onclick="tableCtrl.removeRow(this);">삭제</button>',
				'<button type="button" onclick="tableCtrl.upRow(this);">▲</button>',
				'<button type="button" onclick="tableCtrl.downRow(this);">▼</button>'
			].join('');
		}
	},
	upRow: function(el){
		var row = elementCtrl.findParent(el, 'TR');
		elementCtrl.movePre(row);
	},
	downRow: function(el){
		var row = elementCtrl.findParent(el, 'TR');
		elementCtrl.moveNext(row);
	},
	getCellSum: function(table, colIndex){
		var sum = 0;
		var rows = table.rows;
		
		for (var i = 0, l = rows.length; i < l; i++) {
			var val = rows[i].cells[colIndex].innerHTML;
			sum += parseInt(val);
		}
		return sum;
	}
};
var pageCtrl = {
	loadData: function(){
		var table = document.getElementsByTagName('table')[0].tBodies[0];
		var basicDataList = [
			{"title": "점심", "price": 5000},
			{"title": "영화", "price": 9000},
			{"title": "커피", "price": 4000}
		];
		tableCtrl.insertRow(basicDataList, table);
	},
	addData: function(){
		var name = document.getElementsByName('productName')[0].value;
		var price = document.getElementsByName('productPrice')[0].value;
		var datas = [{
			"title": name,
			"price": price
		}];
		var table = document.getElementsByTagName('table')[0].tBodies[0];
		tableCtrl.insertRow(datas, table);
	},
	getSum: function(){
		var table = document.getElementsByTagName('table')[0].tBodies[0];
		var sum = tableCtrl.getCellSum(table, 1);
		document.getElementById('priceSum').innerHTML = sum;
	}
};
